package com.jlz.managers.def;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.jlz.beans.def.DivisionBean;
import com.julewa.db.Store;

/**
 * 
 * 这里小改了一下,
 * 将标签改为了@Service, 这样系统将把这个singleton的实例放到ftl上去,
 * 页面上也就可以直接使用${Divisions.rootDivision}和${Divisions.create()}了,
 * 虽然后者是不提倡的,但事实上可以用.
 * 这样做将极大简化ftl函数的开发,无需再实现Querier了.
 * huang benhua
 */
@Service
public class Divisions{
	public enum TYPE{
		ROOT,
		;
		int index = 0;
		public int getValue(){
			return index;
		}
	}
	private Store<DivisionBean> store = new Store<DivisionBean>(DivisionBean.class);
	private static Long ROOT_ID = 0L;
	private DivisionBean root = null;
	@SuppressWarnings("unused")
	@PostConstruct
	private void init(){
		root = getDivision(ROOT_ID);
		if(root != null)return;
		root = store.create();
		root.setLabel("China");
		root.setFullLabel("");
		root.setID(ROOT_ID);
		//如果是0，构成死循环
		root.setParentId(null);
		root.setLevel(0);
		root.setType(TYPE.ROOT.getValue());
		//
		store.insert(root);
	}
	public DivisionBean getRootDivision() {
		return root;
	}

	public DivisionBean getDivision(Long id) {
		return store.get(id);
	}
	
	/**
	 * 
	 * @return new DivisionBean The Division has not been insert into database;
	 */
	public DivisionBean create(){
		return store.create();
	}
	
	//在插入的时候,应该同时将自己插入到父节点列表中去或者清除之
	public boolean insert(DivisionBean division){
		//因为没有给ID赋值,所以错了
		division.setID(store.generateID());
		if(store.insert(division)){
			DivisionBean p = division.getParentDivision();
			if(p == null)return true;
			p.setChildrenDivisions(null);
		};
		return false;
	}
	
	
	public boolean update(DivisionBean divi){
		return store.update(divi);
	}
	
	//删除的时候也一样
	public boolean remove(DivisionBean divi){
		//if has children , you can't remove it
		List<DivisionBean> children = divi.getChildrenDivisions();
		if (CollectionUtils.isEmpty(children)) { 
			if(store.delete(divi)){
				DivisionBean p = divi.getParentDivision();
				if(p == null)return true;
				p.setChildrenDivisions(null);
				return true; 
			}
		}
		return false;
	}
	
	public List<DivisionBean> getChildrenOf(DivisionBean division){
		List<DivisionBean> ls = store.select("children", division);
		if(ls == null)return new ArrayList<DivisionBean>();
		return ls;
	}
	
	public List<DivisionBean> getParentsOf(DivisionBean division){
		DivisionBean p = division.getParentDivision();
		if(p == null)return new ArrayList<DivisionBean>();
		List<DivisionBean> list = new ArrayList<DivisionBean>(p.getParentDivisions());
		list.add(p);
		return list;
	}
	
}
